package com.jjwxc.jwjskandriod.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.google.android.material.tabs.TabLayout;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.activity.BookDetailsActivity;
import com.jjwxc.jwjskandriod.activity.MainActivity;
import com.jjwxc.jwjskandriod.activity.MoreBookActivity;
import com.jjwxc.jwjskandriod.activity.VipInfoActivity;
import com.jjwxc.jwjskandriod.adapter.AllSuggestViewHolder;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFActivity;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.imageloader.FFImageLoader;
import com.jjwxc.jwjskandriod.framework.refresh.XRefreshView;
import com.jjwxc.jwjskandriod.framework.refresh.recyclerview.BaseRecyclerAdapter;
import com.jjwxc.jwjskandriod.framework.utils.FFUtils;
import com.jjwxc.jwjskandriod.framework.utils.PreUtils;
import com.jjwxc.jwjskandriod.framework.utils.StUtils;
import com.jjwxc.jwjskandriod.model.ListUserBookRequest;
import com.jjwxc.jwjskandriod.model.ListUserBookResponse;
import com.jjwxc.jwjskandriod.model.TagListResopnse;
import com.jjwxc.jwjskandriod.model.UserProfileRequest;
import com.jjwxc.jwjskandriod.model.UserRecomBook;
import com.jjwxc.jwjskandriod.readActivity.utils.StringUtils;
import com.jjwxc.jwjskandriod.readActivity.utils.UMConstant;
import com.jjwxc.jwjskandriod.widget.InterestPop;
import com.jjwxc.jwjskandriod.widget.LinearLayouDecoration;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

public class AllSuggestFragment extends Fragment implements View.OnClickListener {
    private View view;
    TabLayout tab_other_more;
    RadioGroup tab_otherstack_layout;

    RecyclerView rv_space;

    TextView tv_title_more;
    TextView tv_username;
    LinearLayout ll_one;
    LinearLayout ll_newuser;
    ConstraintLayout cl_two;
    ConstraintLayout cl_my_one;
    ConstraintLayout cl_my_two;

    TextView tv_time;
    TextView tv_moth;
    ImageView img_viptrue;
    ImageView img_vipicon;
    ImageView img_vip_icon;

    TextView tv_other_vip;
    TextView tv_vipc;
    TextView tv_details;
    LinearLayout ll_title_g;
    private InfoSuggestAdapter adapter;
    private XRefreshView refreshView;
    public static long lastRefreshTime;
    private int page;
    String mSelectTab;
    ListUserBookRequest mRequest;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_allsuggest, container, false);
            tab_other_more = view.findViewById(R.id.tab_other_more);
            tab_otherstack_layout = view.findViewById(R.id.tab_otherstack_layout);
            tv_title_more = view.findViewById(R.id.tv_title_more);
            rv_space = view.findViewById(R.id.view_otherstack_pager);
            tv_username = view.findViewById(R.id.tv_username);
            ll_one = view.findViewById(R.id.ll_one);
            cl_two = view.findViewById(R.id.cl_two);
            tv_moth = view.findViewById(R.id.tv_moth);
            tv_time = view.findViewById(R.id.tv_time);
            tv_other_vip = view.findViewById(R.id.tv_other_vip);
            tv_vipc = view.findViewById(R.id.tv_vipc);
            img_viptrue = view.findViewById(R.id.img_viptrue);
            img_vipicon = view.findViewById(R.id.img_vipicon);
            img_vip_icon = view.findViewById(R.id.img_vip_icon);
            tv_details = view.findViewById(R.id.tv_details);
            cl_my_one = view.findViewById(R.id.cl_my_one);
            cl_my_two = view.findViewById(R.id.cl_my_two);
            ll_newuser = view.findViewById(R.id.ll_newuser);
            ll_title_g = view.findViewById(R.id.ll_title_g);
            refreshView = view.findViewById(R.id.allsuggest_view);

            tv_title_more.setOnClickListener(this);
            tv_details.setOnClickListener(this);
            cl_my_one.setOnClickListener(this);
            cl_my_two.setOnClickListener(this);
            ll_title_g.setOnClickListener(this);

            refreshView.setPinnedTime(1000);
            refreshView.setMoveForHorizontal(true);
            refreshView.setPullRefreshEnable(true);
            refreshView.setPullLoadEnable(true);
            refreshView.setAutoLoadMore(true);
            refreshView.enableReleaseToLoadMore(true);
            refreshView.enableRecyclerViewPullUp(true);
            refreshView.enablePullUpWhenLoadCompleted(true);

            // 设置上次刷新的时间
            refreshView.restoreLastRefreshTime(lastRefreshTime);
            rv_space.setLayoutManager(new LinearLayoutManager(getActivity()));

            rv_space.addItemDecoration(new LinearLayouDecoration(getActivity(), LinearLayouDecoration.HORIZONTAL, R.dimen.border18, R.color.transparent));
            rv_space.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题

            rv_space.setLayoutManager(new LinearLayoutManager(getActivity()) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            adapter = new InfoSuggestAdapter(getActivity());
            rv_space.setAdapter(adapter);

            //初始化请求条件
            String hobby = PreUtils.getString("Interest_Hobby", "");
            if (StringUtils.isEmpty(hobby)) {
                mRequest = new ListUserBookRequest();
                mRequest.setLimit(10);
                mRequest.setOffset(0);

            } else {
                mRequest = JSON.parseObject(hobby, ListUserBookRequest.class);

            }

            refreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
                @Override
                public void onRefresh(boolean isPullDown) {
                    page = 0;
                    getUserProfile();
                    postListDate();
                }

                @Override
                public void onLoadMore(boolean isSilence) {
                    super.onLoadMore(isSilence);
                    page += 1;
                    postDate(page * 10, mRequest);
                }
            });
            getUserProfile();
            postListDate();
        }
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (PreUtils.getInt("app_bg", 0) == 0) {
            ll_newuser.setBackgroundResource(R.mipmap.new_bg_one);
        } else if (PreUtils.getInt("app_bg", 0) == 2) {
            ll_newuser.setBackgroundResource(R.mipmap.new_bg_two);
        } else if (PreUtils.getInt("app_bg", 0) == 1) {
            ll_newuser.setBackgroundResource(R.mipmap.new_bg_three);
        } else {
            ll_newuser.setBackgroundResource(R.mipmap.new_bg_one);
        }
        MobclickAgent.onEvent(getContext(), UMConstant.SUGGEST_TUIJIAN_NEW);
        MobclickAgent.onEvent(getContext(), UMConstant.SUGGEST_TUIJIAN_GUESS);
    }

    public void getUserProfile() {
        ((FFActivity) getActivity()).post(Url.getUserProfile, null, UserProfileRequest.class, new FFNetWorkCallBack<UserProfileRequest>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(UserProfileRequest response) {
                if (response.getCode() == 200) {
                    UserProfileRequest.DataBean.MonthSubscribeInfoBean moth = response.getData().getMonthSubscribeInfo();
                    UserProfileRequest.DataBean.VipInfoBean vipInfoBean = response.getData().getVipInfo();
                    //包月信息+vip
                    if (moth.isIsMonthSubscribe() && vipInfoBean.isIsNewUserGift() && vipInfoBean.isIsVip()) {
                        tv_username.setText("欢迎您，亲爱的" + response.getData().getNickname() + "送您好礼助力阅读");
                        ll_one.setVisibility(View.VISIBLE);
                        cl_two.setVisibility(View.GONE);
                        img_vip_icon.setVisibility(View.GONE);
                        tv_time.setText("还剩" + FFUtils.getBetweenTimeDay(vipInfoBean.getExpiredTime()) + "天");
                        tv_moth.setText("还剩" + FFUtils.getBetweenTimeDay(moth.getExpiredTime()) + "天");
                    }
                    //不是新用户包月信息+vip
                    else if (moth.isIsMonthSubscribe() && !vipInfoBean.isIsNewUserGift() && vipInfoBean.isIsVip()) {
                        tv_username.setText("欢迎您，亲爱的" + response.getData().getNickname());
                        ll_one.setVisibility(View.VISIBLE);
                        cl_two.setVisibility(View.GONE);
                        img_vip_icon.setVisibility(View.GONE);
                        tv_time.setText("还剩" + FFUtils.getBetweenTimeDay(vipInfoBean.getExpiredTime()) + "天");
                        tv_moth.setText("还剩" + FFUtils.getBetweenTimeDay(moth.getExpiredTime()) + "天");
                    }
                    //新用户次月，是vip，是新用户，但是没包月了
                    else if (vipInfoBean.isIsVip() && vipInfoBean.isIsNewUserGift() && !moth.isIsMonthSubscribe()) {
                        ll_one.setVisibility(View.GONE);
                        img_vipicon.setVisibility(View.GONE);
                        img_vip_icon.setVisibility(View.GONE);
                        cl_two.setVisibility(View.VISIBLE);
                        img_viptrue.setVisibility(View.VISIBLE);
                        tv_username.setText("欢迎您，亲爱的" + response.getData().getNickname() + "送您好礼助力阅读");
                        tv_other_vip.setText("有效期" + FFUtils.stringToDate(vipInfoBean.getExpiredTime() + "")
                                + "  还剩" + FFUtils.getBetweenTimeDay(vipInfoBean.getExpiredTime()) + "天");
                        tv_vipc.setText("VIP购书六折，专享装扮");

                    }
                    //老用户VIP,是vip，但是不是新用户福利，没有包月
                    else if (vipInfoBean.isIsVip() && !vipInfoBean.isIsNewUserGift() && !moth.isIsMonthSubscribe()) {
                        ll_one.setVisibility(View.GONE);
                        img_vipicon.setVisibility(View.GONE);
                        img_vip_icon.setVisibility(View.GONE);
                        cl_two.setVisibility(View.VISIBLE);
                        img_viptrue.setVisibility(View.VISIBLE);
                        tv_username.setText("欢迎您，亲爱的" + response.getData().getNickname());
                        tv_other_vip.setText("有效期" + FFUtils.stringToDate(vipInfoBean.getExpiredTime() + "")
                                + "  还剩" + FFUtils.getBetweenTimeDay(vipInfoBean.getExpiredTime()) + "天");
                        tv_vipc.setText("VIP购书六折，专享装扮");
                    }
                    //老用户包月,不是是vip，不是新用户福利，有包月
                    else if (!vipInfoBean.isIsVip() && !vipInfoBean.isIsNewUserGift() && moth.isIsMonthSubscribe()) {
                        img_viptrue.setVisibility(View.GONE);
                        ll_one.setVisibility(View.GONE);
                        img_vipicon.setVisibility(View.GONE);
                        img_vip_icon.setVisibility(View.GONE);
                        cl_two.setVisibility(View.VISIBLE);
                        tv_username.setText("欢迎您，亲爱的" + response.getData().getNickname());
                        tv_other_vip.setText("万本包月书免费读");
                        tv_vipc.setText("有效期" + FFUtils.stringToDate(moth.getExpiredTime() + "")
                                + "  还剩" + FFUtils.getBetweenTimeDay(moth.getExpiredTime()) + "天");
                    }
                    //老用户非VIP,不是vip，不是新用户福利，没有包月
                    else if (!PreUtils.getBoolean("tourist", false) && !vipInfoBean.isIsVip() && !vipInfoBean.isIsNewUserGift() && !moth.isIsMonthSubscribe()) {
                        img_viptrue.setVisibility(View.GONE);
                        ll_one.setVisibility(View.GONE);
                        cl_two.setVisibility(View.VISIBLE);
                        img_vipicon.setVisibility(View.GONE);
                        img_vip_icon.setVisibility(View.VISIBLE);
                        tv_username.setText("欢迎您，亲爱的" + response.getData().getNickname());
                        tv_other_vip.setText("再消费" + StUtils.percentage(vipInfoBean.getDistanceMoney()) + "元，尊享VIP特权");
                        tv_vipc.setText("30天累计消费10元，成为VIP，购书六折，专享装扮");
                    }

                }


            }

            @Override
            public boolean onFail(UserProfileRequest response) {
                return false;
            }
        });
    }

    public void postListDate() {

        ((FFActivity) getActivity()).post(Url.listNewUserRecommendBook, null, UserRecomBook.class, new FFNetWorkCallBack<UserRecomBook>() {
            @Override
            public void onSuccess(UserRecomBook response) {
                if (response.getCode() == 200) {
                    refreshView.stopRefresh();
                    lastRefreshTime = refreshView.getLastRefreshTime();
                    setTabs(tab_other_more, getLayoutInflater(), response.getData());
                }
            }

            @Override
            public boolean onFail(UserRecomBook response) {
                return false;
            }
        }, "{\"limit\":10}");
        ((FFActivity) getActivity()).post(Url.listTag, null, TagListResopnse.class, new FFNetWorkCallBack<TagListResopnse>() {
            @Override
            public void onSuccess(TagListResopnse response) {
                List<TagListResopnse.DataBean> tabTitle = new ArrayList<>();
                if (response.getCode() == 200) {
                    TagListResopnse.DataBean bean = new TagListResopnse.DataBean();
                    bean.setName("不限");
                    bean.setTagId("");
                    tabTitle.add(bean);
                    tabTitle.addAll(response.getData());
                    setTabList(tab_otherstack_layout, getLayoutInflater(), tabTitle);
                }
            }

            @Override
            public boolean onFail(TagListResopnse response) {
                return false;
            }
        }, "{\"offset\":0,\"limit\":6}");

    }

    /**
     * 设置页卡显示效果
     *
     * @param tabLayout
     * @param inflater
     */
    private void setTabs(TabLayout tabLayout, LayoutInflater inflater, List<UserRecomBook.DataBean> list) {
        tabLayout.removeAllTabs();
        for (int i = 0; i < list.size(); i++) {
            TabLayout.Tab tab = tabLayout.newTab();
            View view = inflater.inflate(R.layout.allsuggest_item_book, null);
            // 使用自定义视图，目的是为了便于修改，也可使用自带的视图
            tab.setCustomView(view);
            ImageView img_grid_book = view.findViewById(R.id.img_grid_book);
            TextView txt_grid_book = view.findViewById(R.id.txt_grid_book);
            FFImageLoader.loadImage(getContext(), img_grid_book, list.get(i).getCoverImgUrl(), list.get(i).getBookId(), true);
            txt_grid_book.setText(list.get(i).getName());
            int finalI = i;
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), BookDetailsActivity.class);
                    intent.putExtra("bookId", list.get(finalI).getBookId());
                    startActivity(intent);
                    MobclickAgent.onEvent(getContext(), UMConstant.SUGGEST_TUIJIAN_NEW_CLICK);
                }
            });
            tabLayout.addTab(tab);
        }
    }

    /**
     * 设置页卡显示效果
     *
     * @param radioGroup
     * @param inflater
     */
    private void setTabList(RadioGroup radioGroup, LayoutInflater inflater, List<TagListResopnse.DataBean> tabTitle) {

        radioGroup.removeAllViews();
        for (int i = 0; i < tabTitle.size(); i++) {
            RadioButton view = (RadioButton) inflater.inflate(R.layout.suggest_tag_item, null);
            view.setId(i);
            ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, FFUtils.getPx(26));
            layoutParams.setMargins(10, 0, 0, 0);
            view.setLayoutParams(layoutParams);
            if (i == 0) {
                view.setChecked(true);
                mSelectTab = tabTitle.get(i).getTagId();
            }
            view.setText(tabTitle.get(i).getName());
            radioGroup.addView(view);
            int finalI = i;
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mSelectTab = tabTitle.get(finalI).getTagId();
                    page = 0;
                    postDate(0, mRequest);
                    MobclickAgent.onEvent(getContext(), UMConstant.SUGGEST_TUIJIAN_GUESS_TAG_CLICK);
                }
            });

        }
        //请求地址
        postDate(0, mRequest);
    }

    /**
     * 网络请求
     *
     * @param page
     * @param request
     */
    public void postDate(int page, ListUserBookRequest request) {
        List<String> list = new ArrayList<>();
        if (!StUtils.isEmpty(mSelectTab)) {
            list.add(mSelectTab);
            request.setTagIds(list);
        }
        request.setOffset(page);
        ((FFActivity) getActivity()).post(Url.listUserInterestBook, null, ListUserBookResponse.class, new FFNetWorkCallBack<ListUserBookResponse>() {
            @Override
            public void onSuccess(ListUserBookResponse response) {

                lastRefreshTime = refreshView.getLastRefreshTime();
                if (response.getCode() == 200) {
                    if (response.getData() == null || response.getData().size() <= 0) {
                        refreshView.setLoadComplete(true);
                    }
                    if (page == 0) {
                        refreshView.setLoadComplete(false);
                        adapter.setData(response.getData());
                    } else {
                        refreshView.stopLoadMore();
                        adapter.addData(response.getData());
                    }

                }

            }

            @Override
            public boolean onFail(ListUserBookResponse response) {
                return false;
            }
        }, JSON.toJSONString(request));


    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_title_more) {
            Intent intent = new Intent(getActivity(), MoreBookActivity.class);
            intent.putExtra("MORE_Url", Url.listNewUserRecommendBook);
            intent.putExtra("MORE_Name", "新用户专享书籍推荐");
            intent.putExtra("MORE_Key", "no");
            startActivity(intent);
            MobclickAgent.onEvent(getContext(), UMConstant.SUGGEST_TUIJIAN_NEW_MORE_CLICK);
        } else if (v.getId() == R.id.tv_details) {
            Intent intent = new Intent();
            intent.setAction(MainActivity.RefreshMy);
            getActivity().sendBroadcast(intent);
        } else if (v.getId() == R.id.cl_my_one) {
            Intent intent = new Intent(getActivity(), VipInfoActivity.class);
            startActivity(intent);
        } else if (v.getId() == R.id.cl_my_two) {
            Intent intent = new Intent();
            intent.setAction(MainActivity.RefreshStack);
            getActivity().sendBroadcast(intent);
        } else if (v.getId() == R.id.ll_title_g) {
            new InterestPop().interestPopWindow(v, getActivity(), new InterestPop.PopInterestListener() {
                @Override
                public void onValueClick(ListUserBookRequest value) {
                    mRequest = value;
                    page = 0;
                    if (value != null) {
                        RadioButton radioButton = (RadioButton) tab_otherstack_layout.getChildAt(0);
                        radioButton.setChecked(true);
                    }
                    //请求地址
                    postDate(0, mRequest);
                }
            });
            MobclickAgent.onEvent(getContext(), UMConstant.SUGGEST_TUIJIAN_GUESS_CHANGE_CLICK);
        }
    }

    public class InfoSuggestAdapter extends BaseRecyclerAdapter<AllSuggestViewHolder> {
        private Context context;


        private List<ListUserBookResponse.DataBean> mData = new ArrayList<>();


        public InfoSuggestAdapter(Context cnt) {
            this.context = cnt;

        }

        @SuppressLint("NotifyDataSetChanged")
        public void addData(List<ListUserBookResponse.DataBean> data) {
            if (data != null) {
                mData.addAll(data);
                notifyDataSetChanged();
            }
        }

        public void setData(List<ListUserBookResponse.DataBean> data) {
            this.mData.clear();
            addData(data);
        }

        /**
         * 创建ViewHolder
         */
        @Override
        public AllSuggestViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) {

            View mView = LayoutInflater.from(context).inflate(R.layout.allsuggest_item_list, parent, false);
            AllSuggestViewHolder viewHolder_text = new AllSuggestViewHolder(mView);
            viewHolder_text.setIsRecyclable(false);
            return viewHolder_text;

        }

        @Override
        public AllSuggestViewHolder getViewHolder(View view) {
            return new AllSuggestViewHolder(view);
        }


        /**
         * 绑定数据：可以直接拿到已经绑定控件的Viewholder对象
         */
        @SuppressLint({"SetTextI18n", "ClickableViewAccessibility"})
        @Override
        public void onBindViewHolder(final AllSuggestViewHolder holder, @SuppressLint("RecyclerView") final int position, boolean isItem) {
            holder.tv_bookname_allsuggest.setText(mData.get(position).getName());
            holder.tv_book_allsuggest.setText(StUtils.reBlank(mData.get(position).getBookIntro()));
            holder.tv_allsuggest_tab.setText(mData.get(position).getChannlname());
            holder.tv_book_author.setText(mData.get(position).getAuthor());
            FFImageLoader.loadImage(getContext(), holder.img_allsuggest_item, mData.get(position).getCoverImgUrl(), mData.get(position).getBookId(), true);

            holder.cl_allsuggest.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), BookDetailsActivity.class);
                    intent.putExtra("bookId", mData.get(position).getBookId());
                    startActivity(intent);
                    MobclickAgent.onEvent(getContext(), UMConstant.SUGGEST_TUIJIAN_GUESS_CELL_CLICK);
                }
            });

        }

        @Override
        public int getAdapterItemViewType(int position) {
            return position;
        }


        @Override
        public int getAdapterItemCount() {
            return mData.size();
        }


    }
}
